<template>
  <div>
    <n-card :bordered="false" class="mt-4 proCard">
      <n-grid cols="2" responsive="screen">
        <n-grid-item offset="0 s:0 m:1 l:1 xl:1 2xl:1">
          <n-form
            :label-width="90"
            :model="formValue"
            :rules="rules"
            label-placement="top"
            ref="formRef"
            class="py-8"
          >
            <n-form-item label="名称" path="title">
              <n-input v-model:value="formValue.title" placeholder="输入名称" />
            </n-form-item>
            <n-form-item label="封面" path="img">
              <BasicUpload
                :action="`${uploadUrl}`"
                :headers="uploadHeaders"
                :data="{ folder: 'node' }"
                name="files"
                :width="200"
                :height="150"
                @upload-change="uploadChange"
                v-model:value="uploadList"
              />
            </n-form-item>
            <n-form-item label="价格" path="price">
              <n-input-number v-model:value="formValue.price" :precision="2" placeholder="价格" />
            </n-form-item>
            <n-form-item label="积分" path="points">
              <n-input-number v-model:value="formValue.points" placeholder="积分" />
            </n-form-item>
            <n-form-item label="分类" path="type_id">
              <n-select v-model:value="formValue.type_id" :options="types" />
            </n-form-item>
            <n-form-item label="网盘链接" path="pan">
              <n-input v-model:value="formValue.pan" placeholder="输入名称" />
            </n-form-item>
            <n-form-item label="附件" path="files">
              <n-input v-model:value="formValue.files" placeholder="输入名称" />
            </n-form-item>
            <n-form-item label="详情" path="content">
              <n-card :bordered="false" class="mt-4 proCard">
                <QuillEditor
                  ref="quillEditor"
                  :options="options"
                  v-model:content="editorContent"
                  style="height: 350px"
                  @ready="readyQuill"
                  class="quillEditor"
                />
              </n-card>
            </n-form-item>
            <div style="margin-left: 80px">
              <n-space>
                <n-button type="primary" @click="formSubmit">提交</n-button>
                <n-button @click="resetForm">重置</n-button>
              </n-space>
            </div>
          </n-form>
        </n-grid-item>
      </n-grid>
    </n-card>
  </div>
</template>

<script lang="ts" setup>
  import { ref, unref, reactive, onMounted } from 'vue';
  import { useMessage } from 'naive-ui';
  import { BasicUpload } from '@/components/Upload';
  import { useGlobSetting } from '@/hooks/setting';
  import { QuillEditor } from '@vueup/vue-quill';
  import '@vueup/vue-quill/dist/vue-quill.snow.css';
  import { ResultEnum } from '@/enums/httpEnum';
  import { useRouter } from 'vue-router';
  import { useUser } from '@/store/modules/user';
  import { getType } from '@/api/type/type';
  import { getNodeInfo, patchNode, putNode } from '@/api/node/node';

  const id: any = ref(useRouter().currentRoute.value.params.id);
  const quillEditor = ref();
  const editorContent = ref<string>('');
  const globSetting = useGlobSetting();
  const rules = {
    title: {
      required: true,
      message: '请输入节点名称',
      trigger: 'blur',
    },
  };

  let types = ref<any>([]);
  const formRef: any = ref(null);
  const message = useMessage();
  const { uploadUrl } = globSetting;

  const defaultValueRef = () => ({
    id: 0,
    title: '',
    cover: [''],
    type_id: 0,
    pan: '',
    price: 0,
    points: 0,
    sort: 1,
    files: '',
    status: '',
    content: '',
  });

  let formValue = reactive(defaultValueRef());
  const uploadList = ref([]);
  const uploadHeaders = reactive({
    platform: 'miniPrograms',
    timestamp: new Date().getTime(),
    Authorization: 'Bearer ' + useUser().getToken,
  });

  const getTypes = async () => {
    const response: any = await getType({ model: 'Node' });
    response.data.forEach((element: any) => {
      types.value.push({ label: element.title, value: element.id });
    });
  };

  const getData = async () => {
    const response: any = await getNodeInfo(formValue.id);
    if (response.code === ResultEnum.SUCCESS) {
      response.data.price = parseFloat(response.data.price);
      response.data.content = response.data.content.replace(/crossorigin="anonymous"/gi, '');
      response.data.content = response.data.content.replace(/section/gi, 'p');
      quillEditor.value.setHTML(response.data.content);
      let cover: any = [];
      cover.push(response.data.cover);
      uploadList.value = cover;
      Object.assign(formValue, response.data);
    }
  };

  function formSubmit() {
    formRef.value.validate(async (errors) => {
      if (!errors) {
        try {
          formValue.content = quillEditor.value.getHTML();
          let response: any = null;
          if (formValue.id == 0) {
            response = await putNode(formValue);
          } else {
            response = await patchNode(formValue);
          }

          if (response.code === ResultEnum.SUCCESS) {
            Object.assign(formValue, response.data);
            message.success('操作成功');
          }
        } finally {
          // loading.value = false;
        }
      } else {
        message.error('验证失败，请填写完整信息');
      }
    });
  }

  const options = reactive({
    modules: {
      toolbar: [
        ['bold', 'italic', 'underline', 'strike'], // toggled buttons
        ['blockquote', 'code-block'],

        [{ header: 1 }, { header: 2 }], // custom button values
        [{ list: 'ordered' }, { list: 'bullet' }],
        [{ script: 'sub' }, { script: 'super' }], // superscript/subscript
        [{ indent: '-1' }, { indent: '+1' }], // outdent/indent
        [{ direction: 'rtl' }], // text direction

        [{ size: ['small', false, 'large', 'huge'] }], // custom dropdown
        [{ header: [1, 2, 3, 4, 5, 6, false] }],

        [{ color: [] }, { background: [] }], // dropdown with defaults from theme
        [{ font: [] }],
        [{ align: [] }],
        ['clean'],
        ['image'],
      ],
    },
    theme: 'snow',
    placeholder: '输入内容！',
  });

  function readyQuill() {
    console.log('Quill准备好了');
  }

  function resetForm() {
    formRef.value.restoreValidation();
    formValue = Object.assign(unref(formValue), defaultValueRef());
  }

  function uploadChange(list: string[]) {
    formValue.cover = unref(list);
  }

  onMounted(() => {
    formValue.id = id.value;
    if (formValue.id != 0) {
      getData();
    }
    getTypes();
  });
</script>

<style lang="less">
  .ql-toolbar.ql-snow {
    border-top: none;
    border-left: none;
    border-right: none;
    border-bottom: 1px solid #eee;
    margin-top: -10px;
  }

  .ql-container.ql-snow {
    border: none;
  }
</style>
